import json
from operator import itemgetter, attrgetter

from flask import Blueprint, render_template, redirect, url_for, flash, request, jsonify, current_app
from flask_login import login_user, logout_user, login_required, current_user
from werkzeug.security import generate_password_hash, check_password_hash
from application import db
from application.users.forms import RegisterForm, LoginForm
from application.users.models import Users


# 生成一个蓝图对象
users = Blueprint('users', __name__)

# 实际url会是:/users/register
# 用户注册
@users.route('/register', methods=['GET', 'POST'])
def register():
    form = RegisterForm()
    # 验证表单
    if form.validate_on_submit():
        username = form.username.data
        password = form.password.data
        fullname = form.fullname.data
        password_hash = generate_password_hash(password)

        # 新增用户到数据库
        user = Users(username=username, password=password_hash, fullname=fullname)
        db.session.add(user)
        db.session.commit()
        # 自动登录
        login_user(user, remember=False)
        # flash('登录成功!欢迎来到小白鼠!')
        flash('恭喜你!注册成功!')
        return redirect(url_for('users.select_class'))

        # 跳转到选班级页面
        # flash('恭喜你!注册成功!')
        # return redirect(url_for('users.select_class'))

    return render_template('users/register.html', form=form)


# 用户登录
@users.route('/login', methods=['GET', 'POST'])
def login():
    form = LoginForm()
    if form.validate_on_submit():
        # 判断用户是否存在数据库
        username = form.username.data
        user = Users.query.filter_by(username=username).first()
        if not user:
            flash('用户名或密码错误!')
            return render_template('users/login.html', form=form)

        # 判断密码是否正确
        password = form.password.data
        if check_password_hash(user.password, password):
            # 自动登录
            login_user(user, remember=form.remember_me)
            flash('登录成功!欢迎来到小白鼠!')
            return redirect(url_for('users.select_class'))

        flash('用户名或密码错误!')
    return render_template('users/login.html', form=form)

# 用户登出
@users.route('/logout')
def logout():
    logout_user()
    flash('成功登出')
    return redirect(url_for('home.index'))

# 改变用户当期听课状态{'听课状态': 'stop'}
@users.route('/change_listen_status', methods=['POST'])
def change_listen_status():
    # 拿到所有json数据
    json_data_str = request.get_data(as_text=True)
    json_data = json.loads(json_data_str)

    if 'listen_status' not in json_data:
        return jsonify({'status': '缺失listen_status', 'status_code': '1001'})
    listen_status = json_data.get('listen_status')
    current_user.current_listen_status = listen_status
    db.session.add(current_user)
    db.session.commit()
    # jsonify会返回mime类型为text/json的格式,前端可以直接用
    return jsonify({'status': 'ok', 'status_code': '200'})

# 显示所有用户
@users.route('all_users')
@login_required
def all_users():
    page = request.args.get('page', 1, type=int)

    select_type = request.args.get('select_type', 'username', type=str)

    order_str = request.args.get('order', 'False', type=str)
    # request.args.get()

    pagination = Users.query.order_by(Users.id.desc()).paginate(
        page, per_page=current_app.config['COUNT_PER_PAGE'], error_out=False)

    users1 = pagination.items
    # reverse=True降序
    order = True
    if order_str == 'False':
        order = False
    elif order_str == 'True':
        order = True

    users = sorted(users1, key=attrgetter('%s' % select_type), reverse=order)

    order = not order
    if order:
        order_str = 'True'
    else:
        order_str = 'False'

    return render_template('users/all_users.html', users=users, pagination=pagination,
                           order=order_str, select_type=select_type)





